﻿#include "timeview.h"
#include <QDateTime>
#include <QMouseEvent>
#include <QApplication>
#include <QHBoxLayout>


int TimeView::m_id = qRegisterMetaType<TimeView*>();

TimeView::TimeView(QWidget *parent)
    :ViewObject(parent)
    ,m_timer(NULL)
    ,m_labelTime(NULL)
    ,m_timeViewParam(NULL)
{
    setWindowFlags(Qt::FramelessWindowHint);
     setAttribute(Qt::WA_DeleteOnClose);
    m_labelTime = new QLabel(this);
    m_labelTime->setAlignment(Qt::AlignCenter);
    m_labelTime->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    m_layout->addWidget(m_labelTime, 0, Qt::AlignCenter);

#ifdef __linux__
    setFocusPolicy(Qt::NoFocus);
#else
    setFocusPolicy(Qt::StrongFocus);
#endif

    if (m_objectParam == NULL)
        m_objectParam = new ParamObject;

    if (m_timer == NULL)
        m_timer = new QTimer(this);

    if (m_timeViewParam == NULL)
        m_timeViewParam = new TimeViewParam;

    connect(m_timer, SIGNAL(timeout()), this, SLOT(TimeOutSlot()));
}

TimeView::~TimeView()
{
    if (m_timeViewParam != NULL)
    {
        delete m_timeViewParam;
        m_timeViewParam = NULL;
    }

    if (m_objectParam != NULL)
    {
        delete m_objectParam;
        m_objectParam = NULL;
    }
}

QString TimeView::GetTimeStrFromFormat(QDateTime datetime, QString format)
{
    //遵循ISO 639-1标准语言代码
    QLocale locale_zh_cn = QLocale("zh_cn");
    QString default_str = locale_zh_cn.toString(datetime, "yyyy-MM-dd dddd hh:mm:ss");
    if (format != "")
    {
        if (!format.contains("##"))
        {
            //不包含##可单独显示格式化信息
            if (!format.contains("@@"))
                return locale_zh_cn.toString(datetime, format);//直接显示格式化信息
            else
            {
                //中英文切换  dddd@@en_us  只支持一个字段
                QStringList list = format.split("@@");
                if (list.size() > 2)
                    return default_str;
                QLocale locale = QLocale(list.at(1));
                return locale.toString(datetime, list.at(0));
            }
        }
        else
        {
            QString ret = "";
            QStringList list = format.split("##");
            for (int i = 0; i < list.size(); i++)
            {
                if (list.at(i).contains("@@"))
                {
                    QStringList list_language = list.at(i).split("@@");
                    if (list_language.size() > 2)
                        return default_str;
                    QLocale locale = QLocale(list_language.at(1));
                    ret += locale.toString(datetime, list_language.at(0));
                }
                else
                {
                    //遵循ISO 639-1标准语言代码
                    ret += locale_zh_cn.toString(datetime, list.at(i));
                }
            }
            return ret;
        }
    }

    //返回默认值
    return default_str;
}

void TimeView::TimeOutSlot()
{
    QDateTime datetime;
    if (NULL != m_labelTime)
    {
        datetime = QDateTime::currentDateTime();
        //2018.11.11 以后为有效日期  其他不显示
        if (datetime > QDateTime::fromString("2018/11/11 00:00", "yyyy/MM/dd hh:mm") )
            m_labelTime->setText(GetTimeStrFromFormat(datetime, m_timeViewParam->m_datetime.m_timeFormat));
        else
            m_labelTime->setText("");
    }
}

void TimeView::ShowObject()
{   
     if (!m_timeViewParam || !m_objectParam) return;

    //这个变量暂时只是存储字体大小
    if (m_timeViewParam->m_datetime.m_style != "")
    {
        m_labelTime->setStyleSheet(m_timeViewParam->m_datetime.m_style);
    }

    TimeOutSlot();
    m_timer->start(500);

    location(m_objectParam->GetX(), m_objectParam->GetY(),
                m_objectParam->GetWidth(), m_objectParam->GetHeight());

    m_labelTime->setFixedSize(size());

    show();
}

void TimeView::GetAttribute(std::string& attribute)
{  
    std::string jsonStr;
    Json::Value base;
    Json::StreamWriterBuilder writerBuilder;
    std::ostringstream os;

    base["zindex"] = QString::number(m_objectParam->GetIndex()).toStdString();
    base["stid"] = QString::number(m_objectParam->GetStId()).toStdString();
    base["x"] = QString::number(m_objectParam->GetX()).toStdString();
    base["y"] = QString::number(m_objectParam->GetY()).toStdString();
    base["w"] = QString::number(m_objectParam->GetWidth()).toStdString();
    base["h"] = QString::number(m_objectParam->GetHeight()).toStdString();
    base["name"] = m_objectParam->GetName().toStdString();

    base["timeformat"] = m_timeViewParam->m_datetime.m_timeFormat.toStdString();
    base["style"] = m_timeViewParam->m_datetime.m_style.toStdString();
    std::unique_ptr<Json::StreamWriter> jsonWriter(writerBuilder.newStreamWriter());
    jsonWriter->write(base, &os);
    jsonStr = os.str();

    attribute = jsonStr;
}

void TimeView::SetAttribute(std::string jsonStr)
{
    bool res;
    JSONCPP_STRING errs;
    Json::Value root;
    Json::CharReaderBuilder readerBuilder;
    std::unique_ptr<Json::CharReader> const jsonReader(readerBuilder.newCharReader());
    res = jsonReader->parse(jsonStr.c_str(), jsonStr.c_str()+jsonStr.length(), &root, &errs);

    if (!res || !errs.empty())
        LOG_QDEBUG<<__FUNCTION__<<"json parse faild"<<QString::fromStdString(errs);

    if (CheckJsonValueType(root, "zindex", Json::stringValue))
        m_objectParam->SetIndex(QString::fromStdString(root["zindex"].asString()).toInt());

    if (CheckJsonValueType(root, "stid", Json::stringValue))
        m_objectParam->SetStId(QString::fromStdString(root["stid"].asString()).toInt());

    if (CheckJsonValueType(root, "x", Json::stringValue))
        m_objectParam->SetX(QString::fromStdString(root["x"].asString()).toInt());

    if (CheckJsonValueType(root, "y", Json::stringValue))
        m_objectParam->SetY(QString::fromStdString(root["y"].asString()).toInt());

    if (CheckJsonValueType(root, "w", Json::stringValue))
        m_objectParam->SetWidth(QString::fromStdString(root["w"].asString()).toInt());

    if (CheckJsonValueType(root, "h", Json::stringValue))
        m_objectParam->SetHeight(QString::fromStdString(root["h"].asString()).toInt());

    if (CheckJsonValueType(root, "name", Json::stringValue))
        m_objectParam->SetName(QString::fromStdString(root["name"].asString()));

    if (CheckJsonValueType(root, "timeformat", Json::stringValue))
        m_timeViewParam->m_datetime.m_timeFormat = QString::fromStdString(root["timeformat"].asString());

    if (CheckJsonValueType(root, "style", Json::stringValue))
        m_timeViewParam->m_datetime.m_style = QString::fromStdString(root["style"].asString());
}


void TimeView::ParseXML(QDomElement* xmlDomEle)
{
    if (m_timeViewParam == NULL)
        m_timeViewParam = new TimeViewParam;

    m_objectParam->SetIndex((xmlDomEle->attribute("zindex","0")).toInt());
    m_objectParam->SetStId((xmlDomEle->attribute("stid","0")).toInt());
    m_objectParam->SetX((xmlDomEle->attribute("x","0")).toInt());
    m_objectParam->SetY((xmlDomEle->attribute("y","0")).toInt());
    m_objectParam->SetWidth((xmlDomEle->attribute("w","0")).toInt());
    m_objectParam->SetHeight((xmlDomEle->attribute("h","0")).toInt());
    m_objectParam->SetName(xmlDomEle->attribute("name",""));
    QDomNodeList paramlist = xmlDomEle->childNodes();
    for (int listcnt = 0; listcnt < paramlist.count(); listcnt++)
    {
        QDomElement param = paramlist.item(listcnt).toElement();
        if (param.isComment()||param.isNull())
            continue;

        QString temp = param.attribute("timeformat", "");
        if (temp != "")
            m_timeViewParam->m_datetime.m_timeFormat = temp;
        temp = param.attribute("style", "");
        if (temp != "")
            m_timeViewParam->m_datetime.m_style = temp;
    }
}

void TimeView::PacketXML(QDomElement* dom)
{
    QDomDocument document;
    *dom = document.createElement("item");
    dom->setAttribute("type", m_objectParam->GetObjectName());
    dom->setAttribute("zindex",QString::number(m_objectParam->GetIndex()));
    dom->setAttribute("stid",QString::number(m_objectParam->GetStId()));
    dom->setAttribute("x",QString::number(m_objectParam->GetX()));
    dom->setAttribute("y",QString::number(m_objectParam->GetY()));
    dom->setAttribute("w",QString::number(m_objectParam->GetWidth()));
    dom->setAttribute("h",QString::number(m_objectParam->GetHeight()));
    dom->setAttribute("name",m_objectParam->GetName());

    QDomElement dom1 = document.createElement("param");
    dom1.setAttribute("timeformat", m_timeViewParam->m_datetime.m_timeFormat);
    dom->appendChild(dom1);

    QDomElement dom2 = document.createElement("param");
    dom2.setAttribute("style", m_timeViewParam->m_datetime.m_style);
    dom->appendChild(dom2);
}

